package com.ikangtai.shecare.personal;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncState;
import com.ikangtai.shecare.common.eventBusMsg.ChooseStateMsg;
import com.ikangtai.shecare.common.eventBusMsg.StatusMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncStateMsg;
import com.ikangtai.shecare.common.util.ActivityCollector;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;

public class StateActivity extends BaseActivity {

    private TopBar topBar;
    private LinearLayout biyunLinearLayout;
    private LinearLayout beiyunLinearLayout;
    private String typeBind;
    private static final int SAVE_STATUS_OK = 1;
    private static final int SAVE_STATUS_NOK = 2;
    private static final int STATUS_RESULT_CODE = 1;
    private DBManager dbManager;
    private int personalChange;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_personal_state);
        ActivityCollector.addActivity(this);
        personalChange = getIntent().getIntExtra("personalChange", 0);
        if (null != App.getStringUserPreference("bindType"))
            typeBind = App.getStringUserPreference("bindType");
        else typeBind = "bindThermometer";
        App.status = App.memory_preference_userState;
        EventBus.getDefault().register(this);
        dbManager = new DBManager(this);
        initView();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);

        if (typeBind.equals("register"))
            topBar.setLeftButtonVisible(false);

        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });

        View.OnClickListener stateOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.biyun_state:
                        App.status = App.STATUS_BIYUN;
                        EventBus.getDefault().post(new ChooseStateMsg(App.status));
                        if (typeBind.equals("register") && personalChange != 1) {
                            Intent intent = new Intent(StateActivity.this, HealthInfoActivity.class);
                            intent.putExtra("status", App.status);
                            intent.putExtra("type", HealthInfoActivity.REGISTER_INTO);
                            startActivity(intent);
                        }
                        break;
                    case R.id.beiyun_state:
                        App.status = App.STATUS_BEIYUN;
                        EventBus.getDefault().post(new ChooseStateMsg(App.status));
                        if (typeBind.equals("register") && personalChange != 1) {
                            Intent intent = new Intent(StateActivity.this, HealthInfoActivity.class);
                            intent.putExtra("status", App.status);
                            intent.putExtra("type", HealthInfoActivity.REGISTER_INTO);
                            startActivity(intent);
                        }
                        break;
                }

                if (InternetUtil.hasInternet()) {
                    SyncStateMsg syncStateMsg = new SyncStateMsg();
                    syncStateMsg.setSyncInActivity(SyncStateMsg.SYNC_IN_STATEACTIVITY);

                    SyncState syncState = new SyncState(StateActivity.this, syncStateMsg);
                    syncState.syncStateWithNetwork();
                } else {
                    saveState2Local(0);
                }
            }
        };

        biyunLinearLayout = (LinearLayout) findViewById(R.id.biyun_state);
        biyunLinearLayout.setOnClickListener(stateOnClickListener);
        beiyunLinearLayout = (LinearLayout) findViewById(R.id.beiyun_state);
        beiyunLinearLayout.setOnClickListener(stateOnClickListener);
    }

    @Subcriber
    private void syncStateMsg(SyncStateMsg syncStateMsg) {
        if (syncStateMsg.getSyncInActivity().equals(SyncStateMsg.SYNC_IN_STATEACTIVITY))
            saveStatus();
    }

    private void saveStatus() {
        AppLog.i("save status! status = " + App.status + ", auth token! token = " + App.authToken);
        OKHttpUtil okHttpClient = new OKHttpUtil(this);

        String appendUrl = "care/switchingStatus.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("status", App.status);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    saveState2Local(0);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            AppLog.i("save status onResponse success!");
                            saveState2Local(1);
                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            OKHttpUtil.setNewToken();
                            saveStatus();
                        } else {
                            AppLog.i("save status onResponse failed! respCode is:" + respCode);
                            saveState2Local(0);
                        }
                    } catch (JSONException e) {
                        AppLog.i("save status onResponse failed!");
                        e.printStackTrace();
                        saveState2Local(0);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("save status JSONException!");
            e.printStackTrace();
            saveState2Local(0);
        }
    }

    private void saveState2Local(int isSynced) {
        StatusMsg statusMsg = new StatusMsg();
        dbManager.updateUserPreference(App.userName, "state", String.valueOf(App.status), "isStateSynced", isSynced);
        App.memory_preference_userState = App.status;
        int saveState = (isSynced == 1 ? SAVE_STATUS_OK : SAVE_STATUS_NOK);

        statusMsg.setRespCode(saveState);
        statusMsg.setStatus(App.status);
        EventBus.getDefault().post(statusMsg);
    }

    @Subcriber
    private void saveStatusEventBusMsg(StatusMsg statusMsg) {
        int eventBusCode = statusMsg.getRespCode();

        switch (eventBusCode) {
            case SAVE_STATUS_OK:
            case SAVE_STATUS_NOK:
                if (typeBind.equals("register") && personalChange != 1) {
                    // startActivity(new Intent(StateActivity.this, HealthInfoActivity.class));
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("personal_state", statusMsg.getStatus());
                    setResult(STATUS_RESULT_CODE, intent);
                    finish();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}
